﻿<template>
  <el-dialog v-model="visible" title="工作站选择" width="900px" destroy-on-close>
    <el-form :inline="true" :model="query" class="mb-10">
      <el-form-item label="工作站编号">
        <el-input v-model="query.code" placeholder="请输入工作站编号" clearable />
      </el-form-item>
      <el-form-item v-if="!enforceProcessOnly" label="所属工序">
        <el-input v-model="query.processId" placeholder="请输入工序ID/名称" clearable />
      </el-form-item>
      <el-form-item label="所在车间">
        <el-input v-model="query.workshopId" placeholder="请输入车间ID/名称" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table
      :data="list"
      border
      v-loading="loading"
      @current-change="onCurrentChange"
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column type="index" width="60" label="#" />
      <el-table-column prop="code" label="工作站编号" min-width="120" />
      <el-table-column prop="name" label="工作站名称" min-width="150" />
      <el-table-column prop="location" label="工作站地点" min-width="160" />
      <el-table-column prop="workshopName" label="所在车间" min-width="120">
        <template #default="scope">{{ scope.row.workshopName || scope.row.workshop_id || '-' }}</template>
      </el-table-column>
      <el-table-column prop="processName" label="所属工序" min-width="120">
        <template #default="scope">{{ scope.row.processName || scope.row.process_id || '-' }}</template>
      </el-table-column>
      <el-table-column prop="description" label="备注" min-width="160" />
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.pageNum"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10,20,50,100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <template #footer>
      <el-button @click="emit('update:modelValue', false)">取消</el-button>
      <el-button type="primary" :disabled="!current" @click="confirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { getWorkstationPage } from '@/api/workstation.js'
import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  defaultProcessId: { type: [String, Number], default: '' },
  defaultWorkshopId: { type: [String, Number], default: '' },
  // 强制只展示默认工序下的工作站，并隐藏工序筛选输入
  enforceProcessOnly: { type: Boolean, default: true },
})
const emit = defineEmits(['update:modelValue', 'confirm'])

const visible = ref(false)
watch(() => props.modelValue, (v) => { visible.value = v })
watch(visible, (v) => emit('update:modelValue', v))

const loading = ref(false)
const list = ref([])
const current = ref(null)
const query = ref({ code: '', processId: '', workshopId: '' })
const pagination = ref({ pageNum: 1, size: 10, total: 0 })

const normalizeList = (res) => {
  const data = res?.data ?? res
  if (Array.isArray(data)) return { list: data, total: data.length }
  if (Array.isArray(data?.list)) return { list: data.list, total: Number(data.total||data.totalCount||data.list.length)||0 }
  if (Array.isArray(data?.records)) return { list: data.records, total: Number(data.total||data.totalCount||data.records.length)||0 }
  return { list: [], total: 0 }
}

const buildParams = () => {
  // 兼容后端字段：既传 processId 也传 process_id；为空不传，避免误筛选
  const resolvedProc = props.enforceProcessOnly && props.defaultProcessId !== ''
    ? props.defaultProcessId
    : (query.value.processId || props.defaultProcessId)
  const procNum = resolvedProc === '' || resolvedProc === undefined || resolvedProc === null
    ? undefined
    : Number(resolvedProc)

  const params = {
    code: query.value.code || undefined,
    workshopId: query.value.workshopId || props.defaultWorkshopId || undefined,
  }
  if (procNum !== undefined && !Number.isNaN(procNum)) {
    params.processId = procNum
    params.process_id = procNum
  }
  return params
}

const fetchData = () => {
  loading.value = true
  const params = buildParams()
  // 调试输出（可保留一段时间帮助定位问题）
  console.debug('查询工作站参数:', { pageNum: pagination.value.pageNum, size: pagination.value.size, ...params })
  getWorkstationPage(pagination.value.pageNum, pagination.value.size, params)
    .then(res => {
      const { list: arr, total } = normalizeList(res)
      list.value = arr
      pagination.value.total = total
      if (arr.length === 0) {
        console.warn('未查询到工作站数据，可能是后端字段名不一致或筛选条件不匹配。当前参数:', params)
      }
    })
    .catch(() => {
      ElMessage.error('加载工作站失败')
    })
    .finally(() => loading.value = false)
}

const handleSearch = () => { pagination.value.pageNum = 1; fetchData() }
const resetSearch = () => { query.value = { code: '', processId: '', workshopId: '' }; handleSearch() }
const handleSizeChange = (size) => { pagination.value.size = size; fetchData() }
const handleCurrentChange = (p) => { pagination.value.pageNum = p; fetchData() }
const onCurrentChange = (row) => { current.value = row }
const confirm = () => { if (current.value) { emit('confirm', current.value); visible.value = false } }

watch(visible, (v) => {
  if (v) {
    if (!query.value.processId && props.defaultProcessId) query.value.processId = String(props.defaultProcessId);
    if (!query.value.workshopId && props.defaultWorkshopId) query.value.workshopId = String(props.defaultWorkshopId);
    fetchData()
  }
})
</script>

<style scoped>
.mb-10 { margin-bottom: 10px; }
.pagination-container { display: flex; justify-content: flex-end; margin-top: 10px; }
</style>
